package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * @Description:    文件上传
     * @Author:        wangqingsong
     * @param:           [file]
     * @return:          com.changgou.entity.Result
     * @CreateDate:     2020/11/18 17:13
     */
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) {


        try {
            if (file == null) {
                throw new RuntimeException("文件不存在");
            }

            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null && "".equals(originalFilename)) {
                throw new RuntimeException("文件不存在");
            }

            byte[] bytes = new byte[0];
            bytes = file.getBytes();

            String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, ext);

            String[] uploadResult = FastDFSClient.upload(fastDFSFile);

            //疯转返回结果
            String url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];

            return new Result(true, StatusCode.OK, "文件上传成功", url);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }

}
